package com.mc.fastkit.span

import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Paint.FontMetricsInt
import android.graphics.Shader
import android.text.style.ReplacementSpan

/**
 * 文字渐变
 * @author: MasterChan
 * @date: 2025-08-13 10:19
 */
class GradientFontSpan(
    private val startColor: Int,
    private val endColor: Int,
    private val isVertical: Boolean = false
) : ReplacementSpan() {

    private var textWidth = 0

    override fun getSize(
        paint: Paint,
        text: CharSequence,
        start: Int,
        end: Int,
        fm: FontMetricsInt?
    ): Int {
        textWidth = (paint.measureText(text, start, end)).toInt()
        return textWidth
    }

    override fun draw(
        canvas: Canvas,
        text: CharSequence,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        // 修改y1的值从上到下渐变， 修改x1的值从左到右渐变
        val lg = if (isVertical) {
            LinearGradient(
                0f, 0f, 0f, paint.descent() - paint.ascent(),
                startColor,
                endColor,
                Shader.TileMode.REPEAT
            )

        } else {
            LinearGradient(
                0f, 0f, textWidth.toFloat(), 0f,
                startColor,
                endColor,
                Shader.TileMode.REPEAT
            )
        }
        paint.setShader(lg)
        canvas.drawText(text, start, end, x, y.toFloat(), paint)
    }
}